//
//  FeedbackViewController.m
//  JDong
//
//  Created by liunian on 13-12-13.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "FeedbackViewController.h"
#import "UIPlaceHolderTextView.h"
#import "SNSManager.h"
#import "FeedbackRequest.h"

#define kDefaultBottomBarHeight           38

@interface FeedbackViewController ()<UITextViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,SNSManagerDelegate,ReqDelegate>
@property (nonatomic, retain) UIImageView          *navImageView;

@property (nonatomic, retain) UIView        *containerView;
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) UIImageView          *bottomImageView;
@property (nonatomic, retain) UIPlaceHolderTextView *textView;
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UITapGestureRecognizer *tapRecognizer;
@property (nonatomic, retain) NSString    *name;
@property (nonatomic, retain) NSString    *url;

@property (nonatomic, retain) FeedbackRequest   *reqFeedback;
@end

@implementation FeedbackViewController

- (void)dealloc{
    _reqFeedback.delegate = nil;
    _reqFeedback = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.navImageView];
    [self.view addSubview:self.bottomImageView];
    [self.theTitle setText:@"建议反馈"];
    UIImageView *mid = [[UIImageView alloc] initWithImage:IMGNAMED(@"bg_cell_separator_line.png")];
    [mid setFrame:CGRectMake(8, 150 - 3, 304, 1)];
    [self.containerView addSubview:mid];
    
    UILabel *email = [[UILabel alloc] initWithFrame:CGRectMake(20,150, 70, 20)];
    [email setBackgroundColor:[UIColor clearColor]];
    [email setTextAlignment:ALIGN_LEFT];
    [email setText:@"您的邮箱:"];
    [email setFont:[UIFont fontWithName:@"Verdana" size:14]];
    [email setTextColor:[UIColor darkGrayColor]];
    [email setNumberOfLines:0];
    [email setLineBreakMode:NSUILineBreakModeClip];
    [self.containerView addSubview:email];
    
    [self textView];
    [self textField];
    [self tapRecognizer];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)handleTap:(UITapGestureRecognizer *)tapGesture{
    [self.textView resignFirstResponder];
    [self.textField resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeSina]) {
        
    }else if ([[SNSManager sharedManager] isLoggedInFor:kOFTypeSina]){
    
    }
}

- (BOOL)validateEmail:(NSString*)email{
    if((0 != [email rangeOfString:@"@"].length) &&
       (0 != [email rangeOfString:@"."].length))
    {
        
        NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
        NSMutableCharacterSet* tmpInvalidMutableCharSet = [tmpInvalidCharSet mutableCopy];
        [tmpInvalidMutableCharSet removeCharactersInString:@"_-"];
        
        //使用compare option 来设定比较规则，如
        //NSCaseInsensitiveSearch是不区分大小写
        //NSLiteralSearch 进行完全比较,区分大小写
        //NSNumericSearch 只比较定符串的个数，而不比较字符串的字面值
        NSRange range1 = [email rangeOfString:@"@"
                                      options:NSCaseInsensitiveSearch];
        
        //取得用户名部分
        NSString* userNameString = [email substringToIndex:range1.location];
        NSArray* userNameArray   = [userNameString componentsSeparatedByString:@"."];
        
        for(NSString* string in userNameArray)
        {
            NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet: tmpInvalidMutableCharSet];
            if(rangeOfInavlidChars.length != 0 || [string isEqualToString:@""])
                return NO;
        }
        
        NSString *domainString = [email substringFromIndex:range1.location+1];
        NSArray *domainArray   = [domainString componentsSeparatedByString:@"."];
        
        for(NSString *string in domainArray)
        {
            NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];
            if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])
                return NO;
        }
        
        return YES;
    }
    else // no ''@'' or ''.'' present
        return NO;
}
- (void)showMsg:(NSString *)msg{
    [Util showTipsView:msg];
}
- (void)send:(UIButton *)button{
    
    if ([self.textView.text length] == 0) {
        [self showMsg:@"内容为空!"];
        return;
    }
    
    NSString *email = @"";
    if ([self.textField.text length] > 0) {
        if ([self validateEmail:self.textField.text] == NO ) {
            [self showMsg:@"邮箱不合法!"];
            return;
        }
        email = self.textField.text;
    }
    button.enabled = NO;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    SET_PARAM(email, @"email", params);
    SET_PARAM(self.textView.text, @"content", params);
    [self.reqFeedback sendContent:self.textView.text email:email delegate:self];
}
#pragma mark ReqDelegate
- (void)finishErrorReq:(id)Req errorCode:(int) errorCode message:(NSString *)message{
    [self showMsg:@"反馈失败"];
}

- (void)finishFeedback:(id)Req{
    [self back];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    NSInteger number = [textView.text length];
    if (number > 140) {
        //        [BUAlertView alertWithMessage:@"字符个数不能大于140"];
        textView.text = [textView.text substringToIndex:140];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if([text isEqualToString:@"\n"]) {
        [self send:nil];
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    [UIView beginAnimations:nil context:NULL];
    CGAffineTransform moveTransform = CGAffineTransformMakeTranslation(0.0, -0.0);
    [self.view.layer setAffineTransform:moveTransform];
    self.view.opaque =1;
    [UIView commitAnimations];
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    [UIView beginAnimations:nil context:NULL];
    CGAffineTransform moveTransform = CGAffineTransformMakeTranslation(0.0, 0.0);
    [self.view.layer setAffineTransform:moveTransform];
    self.view.opaque =1;
    [UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    if (self.textField == textField)  //判断是否时我们想要限定的那个输入框
    {
        if ([toBeString length] > 50) { //如果输入框内容大于50则弹出警告
            textField.text = [toBeString substringToIndex:50];
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self send:nil];
    return YES;
}

#pragma mark - getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, kDefaultBottomBarHeight)];
        _navImageView.userInteractionEnabled = YES;
        
        _navImageView.backgroundColor = COLOR_RGB_NAV;
    }
    return _navImageView;
}

- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 260, 40)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        _theTitle.textColor = [UIColor flatWhiteColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight - _kSpaceHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
        
    }
    return _bottomImageView;
}

- (UIView *)containerView{
    if (!_containerView) {
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navImageView.frame), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - CGRectGetHeight(self.navImageView.frame) - kDefaultBottomBarHeight-_kSpaceHeight)];
        [_containerView setBackgroundColor:COLOR_BG_VIEW];
        [self.view addSubview:_containerView];
    }
    return _containerView;
}
- (UITextView *)textView{
    if (!_textView) {
        _textView = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(20, 20, 280, 120)];
        [_textView setBackgroundColor:[UIColor whiteColor]];
        [_textView setReturnKeyType:UIReturnKeySend];
        [_textView setPlaceholder:@"请输入反馈，我们将为您不断改进"];
        [_textView setDelegate:self];
        [_textView setKeyboardType:UIKeyboardTypeDefault];
        [_textView setTextColor:[UIColor darkGrayColor]];
        [_textView setFont:[UIFont fontWithName:@"Verdana" size:16]];
        [self.containerView addSubview:_textView];
    }
    return _textView;
}

- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(90.0f, 150, 210, 20.0f)];
        [_textField setBorderStyle:UITextBorderStyleNone]; //外框类型
        _textField.placeholder = @"填写邮箱，以便我们给您回复"; //默认显示的字
        _textField.secureTextEntry = NO; //密码
        [_textField setDelegate:self];
        [_textField setTextColor:[UIColor getColor:@"a9a9a9"]];
        [_textField setFont:[UIFont fontWithName:@"Verdana" size:16]];
        _textField.autocorrectionType = UITextAutocorrectionTypeNo;
        _textField.keyboardType = UIKeyboardTypeASCIICapable;
        _textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _textField.returnKeyType = UIReturnKeySend;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        [self.containerView addSubview:_textField];
    }
    return _textField;
}

- (UITapGestureRecognizer *)tapRecognizer{
    if (!_tapRecognizer) {
        _tapRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [_tapRecognizer setNumberOfTapsRequired:1];
        _tapRecognizer.delegate = self;
        [self.containerView addGestureRecognizer:_tapRecognizer];
    }
    return _tapRecognizer;
}

- (FeedbackRequest *)reqFeedback{
    if (!_reqFeedback) {
        _reqFeedback = [[FeedbackRequest alloc] init];
    }
    return _reqFeedback;
}
@end
